// lib/pages/scan_page.dart
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import '../controllers/device_manager_controller.dart';

class ScanPage extends StatelessWidget {
  const ScanPage({super.key});

  @override
  Widget build(BuildContext context) {
    final dm = Get.put(DeviceManagerController(), permanent: true);

    return Scaffold(
      appBar: AppBar(
        title: const Text('选择桑拿设备'),
      ),

      body: SafeArea(
        child: Column(
          children: [
            Padding(
              padding: const EdgeInsets.all(12),
              child: Wrap(
                spacing: 12,
                runSpacing: 8,
                crossAxisAlignment: WrapCrossAlignment.center,
                children: [
                  ElevatedButton.icon(
                    onPressed: () {
                      dm.devices.clear();
                      dm.startScan();
                    },
                    icon: const Icon(Icons.search),
                    label: const Text('扫描'),
                  ),

                  OutlinedButton.icon(
                    onPressed: dm.stopScan,
                    icon: const Icon(Icons.stop),
                    label: const Text('停止'),
                  ),

                  const Text(
                    '🟢 实际设备模式',
                    style: TextStyle(
                      color: Colors.green,
                      fontWeight: FontWeight.w600,
                    ),
                  ),
                ],
              ),
            ),

            const Divider(height: 1),

            Expanded(
              child: Obx(() {
                if (dm.devices.isEmpty) {
                  return const Center(child: Text("暂无设备，点击“扫描”开始"));
                }

                return ListView.separated(
                  itemCount: dm.devices.length,
                  separatorBuilder: (_, __) => const Divider(height: 1),
                  itemBuilder: (_, i) {
                    final r = dm.devices[i];
                    final name = r.device.platformName.isEmpty
                        ? "Unknown"
                        : r.device.platformName;

                    return ListTile(
                      leading: const Icon(Icons.bluetooth,
                          color: Colors.blueAccent),
                      title: Text(name),
                      subtitle: Text(
                        "ID: ${r.device.remoteId.str}  RSSI:${r.rssi}",
                      ),
                      onTap: () {
                        Get.snackbar("连接中", "$name ...",
                            snackPosition: SnackPosition.BOTTOM);

                        dm.connectTo(r);
                      },
                    );
                  },
                );
              }),
            ),
          ],
        ),
      ),
    );
  }
}
